﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using DataAccess.BusinessObject;
using DataAccess.DataObject;
using System.Net.Mail;
using System.IO;
using System.Net.Configuration;
using System.Globalization;
using System.Resources;
using System.Security.Cryptography;
using System.Text;

namespace EnmineKaitlin.Common
{
    public class PageBase:System.Web.UI.Page
    {
        public static CultureInfo ci;
        public static ResourceManager rm;
        public static string domain;
        /* constan */
        public CultureInfo culture = new CultureInfo("fr-FR", true);        
        
        public const int HoiDap_CatID = 21;
        public const int DuAnTieuBieu_CatID = 8;
        public const int TinTuc_CatID=2;
        public const int GioiThieu_CatID = 1;
        public const int TuyenDung_CatID = 7;        

        public const int Banner_PostID = 24;
        public const int BannerKhaoSat_PostID = 25;
        public const int BannerTrai_PostID = 26;
        public const int TongQuatDoanhNghiep_PostID = 3;
        public const int LienKet_PostID = 12;
        public const int HoatDong_PostID = 14;        
        public const int LienHe_PostID = 15;        
        public const int Sodo_PostID = 16;
        public const int ThanhVien_PostID = 17;
        public const int DonVi_PostID = 19;

        /* en */
        public const int FAQ_CatID = 22;
        public const int About_PostID = 11;
        public const int About_CatID = 9;
        public const int Carrer_CatID = 16;
        public const int News_CatID = 10;

        public const int FeaturedProjects_CatID = 17;        
        public const int Link_PostID = 13;        
        public const int Contact_PostID = 27;        
        public const int SiteMap_PostID = 28;
        public const int Group_PostID = 18;
        /* end constan */
        public OCategory _OCategory=new OCategory();
        public BCategory _BCategory=new BCategory();
        public BCategory_Post _BCategory_Post=new BCategory_Post();
        public BCategory_Product _BCategory_Product = new BCategory_Product();

        public OPost _OPost = new OPost();
        public BPost _BPost = new BPost();

        public OProduct _OProduct = new OProduct();
        public BProduct _BProduct = new BProduct();

        public OOrder _OOrder = new OOrder();
        public BOrder _BOrder = new BOrder();

        public OCoupon _OCoupon = new OCoupon();
        public BCoupon _BCoupon = new BCoupon();

        public OCoupon_Product _OCoupon_Product = new OCoupon_Product();
        public BCoupon_Product _BCoupon_Product = new BCoupon_Product();

        public OPoll _OPoll = new OPoll();
        public BPoll _BPoll = new BPoll();
        public BOption _BOption = new BOption();
        public OOption _OOption = new OOption();
        public OSurvey _OSurvey = new OSurvey();
        public BSurvey _BSurvey = new BSurvey();
        public OFAQ _OFAQ = new OFAQ();
        public BFAQ _BFAQ = new BFAQ();
        public OEmail _OEmail = new OEmail();
        public BEmail _BEmail = new BEmail();
        public OUser _OUser = new OUser();
        public BUser _BUser = new BUser();
        public ODepartment _ODepartment = new ODepartment();
        public BDepartment _BDepartment = new BDepartment();
        public OGroup _OGroup = new OGroup();
        public BGroup _BGroup = new BGroup();
        public OUserGroup _OUserGroup = new OUserGroup();
        public BUserGroup _BUserGroup = new BUserGroup();
        public OPermission _OPermission = new OPermission();
        public BPermission _BPermission = new BPermission();

        /// <summary>
        /// list post by PostID, if postid=0 list all post
        /// </summary>
        /// <returns></returns>
        public IList<OPost> list_posts(int PostID)
        {
            return _BPost.Get(0);
        }
        /// <summary>
        /// list all category
        /// </summary>
        /// <returns></returns>
        public IList<OCategory> list_category()
        {            
            return _BCategory.Get(0,"vn");
        }
        /// <summary>
        /// Thêm thuộc tính vào link thao tác
        /// </summary>
        /// <param name="e"></param>
        public void BoundFunctionGridview(GridViewRowEventArgs e)
        {            
            Control c = e.Row.Controls[e.Row.Controls.Count - 1];
            if (c.GetType() != typeof(System.Web.UI.WebControls.DataControlFieldCell)) return;
            if (c.Controls.Count > 0)
            {
                for (int i = 0; i < c.Controls.Count; i++)
                {
                    if (c.Controls[i].GetType().ToString() == "System.Web.UI.WebControls.DataControlLinkButton")
                    {
                        LinkButton lb = (LinkButton)c.Controls[i];

                        switch (lb.Text)
                        {
                            case "Xóa":
                                lb.CssClass = "btnDelete";
                                lb.Attributes.Add("title", "Xóa");
                                lb.OnClientClick = "return confirm('Bạn chắc chắn muốn xóa ?');";
                                break;
                            case "Sửa":
                                lb.Attributes.Add("title", "Sửa");
                                lb.CssClass = "btnEdit";
                                break;
                            case "Cập nhật":
                                lb.Attributes.Add("title", "Cập nhật");
                                lb.CssClass = "btnUpdate";
                                break;
                            case "Hủy":
                                lb.Attributes.Add("title", "Hủy");
                                lb.CssClass = "btnNoUpdate";
                                break;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Thêm nút chọn hoặc bỏ chọn tất cả
        /// </summary>
        /// <param name="e"></param>
        public void AddCheckBoxAll(GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                TableCell tbc = e.Row.Cells[0];
                tbc.Width = 20;
                CheckBox cbx = new CheckBox();
                cbx.CssClass = "cbxAll";
                tbc.Controls.Add(cbx);
            }
        }
        /// <summary>
        /// Bind CKEditor + CKFinder
        /// </summary>
        /// <param name="cke"></param>
        public void bindckeditor(CKEditor.NET.CKEditorControl cke)
        {
            CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
            _FileBrowser.BasePath = "/ckfinder/";
            _FileBrowser.SetupCKEditor(cke);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strDateTime"></param>
        /// <returns></returns>
        public string DisplayDateTime(string strDateTime)
        {
            DateTime dt = DateTime.Parse(strDateTime);
            return dt.ToString("dd/MM/yyy hh:mm");
        }
        public string display_language(string LangID)
        {
            if (LangID == "vn") { return "Tiếng Việt"; } 
            else if (LangID == "en") { return "English"; }
            return LangID;
        }
        public string display_status(string Status)
        {
            return ConfigurationManager.AppSettings[Status];
        }
        public string list_category_of_post(int PostID)
        {
            string cat = "";
            foreach (OCategory_Post objCatPost in (_BCategory_Post.Get(PostID)))
            {
                cat += get_category_name(objCatPost.IDCat) + ", ";
            }
            if (cat != "")
            {
                cat = cat.Remove(cat.LastIndexOf(","));
            }
            return cat;
        }
        public string list_category_of_product(int ProductID)
        {
            string cat = "";
            foreach (OCategory_Product objCatProduct in (_BCategory_Product.Get(ProductID)))
            {
                cat += get_category_name(objCatProduct.IDCat) + ", ";
            }
            if (cat != "")
            {
                cat = cat.Remove(cat.LastIndexOf(","));
            }
            return cat;
        }
        /// <summary>
        /// Lấy về tên chuyên mục theo chuyên mục ID
        /// </summary>
        /// <param name="CatID"></param>
        /// <returns></returns>
        public string get_category_name(int CatID)
        {
            if (CatID == 0) {
                return "Không có chuyên mục cha";
            }
            if (_BCategory.Get(CatID,"vn").Count > 0)
            {
                return (_BCategory.Get(CatID, 0, ""))[0].CatName;
            }
            return "";
        }
        public string get_post_name(int PostID)
        {
            if (_BPost.Get(PostID).Count > 0) 
            {
                return _BPost.Get(PostID)[0].Title;
            }
            return "";
        }
        /// <summary>
        /// Lấy về Category ID theo PostID
        /// </summary>
        /// <param name="PostID"></param>
        /// <returns></returns>
        public string the_category_id(int PostID)
        {
            if(_BCategory_Post.Get(PostID).Count>0)
                return _BCategory_Post.Get(PostID)[0].IDCat.ToString();
            return "";
        }
        public bool Send_Email(string SendFrom, List<string> lstSendTo, string Subject, string Body)
        {
            // System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
            // System.Net.Mail.SmtpClient is the alternate class for this in 2.0
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();

            try
            {                             
                MailAddress fromAddress = new MailAddress(SendFrom);

                // You can specify the host name or ipaddress of your server
                // Default in IIS will be localhost 
                //smtpClient.Host = "smtp.gmail.com";

                //Default port will be 25
                //smtpClient.Port = 587;
                smtpClient.EnableSsl = true;                

                //From address will be given as a MailAddress Object
                message.From = fromAddress;

                // To address collection of MailAddress
                foreach (string strEmail in lstSendTo)
                {
                    message.To.Add(strEmail);
                }                
                message.Subject = Subject;                

                //Body can be Html or text format
                //Specify true if it  is html message
                message.IsBodyHtml = true;

                // Message body content
                message.Body = Body;

                // Send SMTP mail
                smtpClient.Send(message);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            return false;
        }        
        protected IList<OOption> list_option(int PollID)
        {
            return _BOption.Get(PollID);
        }
        public static string GetMd5Hash(MD5 md5Hash, string input)
        {

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        // Verify a hash against a string.
        public bool VerifyMd5Hash(string input, string hash)
        {
            MD5 md5Hash = MD5.Create();
            // Hash the input.
            string hashOfInput = GetMd5Hash(md5Hash, input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool CheckPermission(string module)
        {
            if (Session["username"] != null && Session["username"].ToString() != "")
            {
                if (Session["permission"] != null)
                {
                    IList<OPermission> lstPermission = (IList<OPermission>)Session["permission"];
                    foreach(OPermission objPermission in lstPermission)
                    {
                        if (objPermission.IDModule == module) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        public static string ConvertTitleSeo(string textContent)
        {
            string reStr = textContent.ToLower();
            string[] arrKeyReplate = {
		"à",
		"á",
		"ả",
		"ã",
		"ạ",
		"ă",
		"ằ",
		"ắ",
		"ẳ",
		"ẵ",
		"ặ",
		"â",
		"ầ",
		"ấ",
		"ẩ",
		"ẫ",
		"ậ",
		"đ",
		"è",
		"é",
		"ẻ",
		"ẽ",
		"ẹ",
		"ê",
		"ề",
		"ế",
		"ể",
		"ễ",
		"ệ",
		"ì",
		"í",
		"ỉ",
		"ĩ",
		"ị",
		"ỳ",
		"ý",
		"ỷ",
		"ỹ",
		"ỵ",
		"ò",
		"ó",
		"ỏ",
		"õ",
		"ọ",
		"ô",
		"ồ",
		"ố",
		"ổ",
		"ỗ",
		"ộ",
		"ơ",
		"ờ",
		"ớ",
		"ở",
		"ỡ",
		"ợ",
		"ù",
		"ú",
		"ủ",
		"ũ",
		"ụ",
		"ư",
		"ừ",
		"ứ",
		"ử",
		"ữ",
		"ự",
		"$",
		"  ",
		" ",
		"\"",
		"(",
		")",
		":",
		".",
		",",
		"?",
		"$",
		"%",
		"--",
		"/",
		"&",
		"\" _",
		"\" _",
		"+",
		"'",
		"#"
	};
            string[] arrValueReplate = {
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"d",
		"e",
		"e",
		"e",
		"e",
		"e",
		"e",
		"e",
		"e",
		"e",
		"e",
		"e",
		"i",
		"i",
		"i",
		"i",
		"i",
		"y",
		"y",
		"y",
		"y",
		"y",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"u",
		"u",
		"u",
		"u",
		"u",
		"u",
		"u",
		"u",
		"u",
		"u",
		"u",
		"-",
		" ",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-",
		"-"
	};

            for (int i = 0; i <= arrKeyReplate.Length - 1; i++)
            {
                reStr = reStr.Replace(arrKeyReplate[i], arrValueReplate[i]);
            }
            reStr = reStr.Replace("<sub>", "-");
            reStr = reStr.Replace("<-sub>", "-");
            reStr = reStr.Replace("---", "-");
            reStr = reStr.Replace("--", "-");
            reStr = reStr.Replace("c#", "csharp");
            reStr = reStr.Replace("c++", "c-plus-plus");
            reStr = reStr.Replace("%09", "");

            if (reStr.Length > 100)
            {
                reStr = reStr.Substring(0, 100) + "_";
            }

            return reStr;
        }
    }
}
